//package belajarzk.action.maintenance;
//
//import java.util.List;
//
//import org.hibernate.Session;
//import org.hibernate.criterion.MatchMode;
//import org.hibernate.criterion.Order;
//import org.hibernate.criterion.Restrictions;
//import org.zkoss.zk.ui.sys.ExecutionsCtrl;
//import org.zkoss.zul.Comboitem;
//import org.zkoss.zul.Grid;
//import org.zkoss.zul.ListModel;
//import org.zkoss.zul.SimpleListModel;
//import org.zkoss.zul.Textbox;
//import org.zkoss.zul.Window;
//
//import belajarzk.database.dao.DaoFactory;
//import belajarzk.database.dao.TbmuserDao;
//import belajarzk.database.hibernate.HibernateUtil;
//import belajarzk.database.model.Tbmrole;
//import belajarzk.database.model.Tbmuser;
//import belajarzk.ui.render.grid.TbmuserRenderer;
//
//
//public class TbmuserAction {
//
//	@SuppressWarnings("deprecation")
//	public synchronized static void resetInput(Tbmuser users) {
//		Window window = ((Window) ExecutionsCtrl.getCurrentCtrl()
//				.getCurrentPage().getVariable("addWindow"));
//		window.setSizable(true);
//		((Textbox) window.getVariable("add_usersname", true))
//				.setValue(users == null ? "" : users.getUserId());
//		((Textbox) window.getVariable("add_password", true))
//				.setValue(users == null ? "" : users.getUserPassword());
//		((Textbox) window.getVariable("add_passwordRetype", true))
//				.setValue(users == null ? "" : users.getUserPassword());
//		((Textbox) window.getVariable("add_namaLengkap", true))
//				.setValue(users == null ? "" : users.getUserNama());
//
//		org.zkoss.zul.Combobox jobs = (org.zkoss.zul.Combobox) window
//				.getVariable("role", true);
//
//		if (users != null) {
//			for (Object item : jobs.getItems()) {
//				Comboitem comboitem = (Comboitem) item;
//				Tbmrole comboTbmrole = (Tbmrole) comboitem.getValue();
//				if (comboTbmrole.getRoleId().equals(
//						users.getUserRole().getRoleId())) {
//					jobs.setSelectedItem(comboitem);
//				}
//			}
//		} else {
//			jobs.setSelectedItem(null);
//		}
//
//	}
//
//	public void save(Tbmuser users) {
//
//		// Window window = ((Window) ExecutionsCtrl.getCurrentCtrl()
//		// .getCurrentPage().getVariable("addWindow"));
//
//		// Checkbox checkbox = new Checkbox();
//
//		TbmuserDao usersDao = DaoFactory.getInstance().getTbmuserDao();
//		Tbmuser tbmuser = (Tbmuser) usersDao.getCurrentSession()
//				.createCriteria(Tbmuser.class).add(
//						Restrictions.idEq(users.getUserId())).uniqueResult();
//
//		// usersDao.beginTransaction();
//		if (tbmuser == null) {
//			usersDao.save(users);
//		} else {
//			usersDao.update(users);
//		}
//		// usersDao.commitTransaction();
//		search(new Tbmuser());
//
//		resetInput(null);
//
//	}
//
//	@SuppressWarnings("unchecked")
//	public void search(Tbmuser usersLike) {
//
//		usersLike = new Tbmuser();
//
//		usersLike.setUserId(((Textbox) ExecutionsCtrl.getCurrentCtrl()
//				.getCurrentPage().getVariable("usersname")).getValue());
//
//		Session session = HibernateUtil.currentSession();
//		List<Tbmuser> users = session.createCriteria(Tbmuser.class).addOrder(
//				Order.desc("userId")).add(
//				Restrictions.ilike("userId", usersLike.getUserId() == null ? ""
//						: usersLike.getUserId(), MatchMode.ANYWHERE)).add(
//				Restrictions.ilike("userNama",
//						usersLike.getUserNama() == null ? "" : usersLike
//								.getUserNama(), MatchMode.ANYWHERE)).add(
//				usersLike.getUserRole() == null ? Restrictions
//						.sqlRestriction("1=1") : Restrictions.eq("userRole",
//						usersLike.getUserRole())).setMaxResults(
//				belajarzk.common.Common.MAX_RESULT).list();
//
//		ListModel strset = new SimpleListModel(users);
//
//		Grid grid = (Grid) ExecutionsCtrl.getCurrentCtrl().getCurrentPage()
//				.getVariable("grid");
//		grid.setRowRenderer(new TbmuserRenderer());
//		grid.setModel(strset);
//		grid.setFixedLayout(true);
//		grid.renderAll();
//
//	}
//
//}
package belajarzk.action.maintenance;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zul.Borderlayout;
import org.zkoss.zul.Caption;
import org.zkoss.zul.Center;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Combobox;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Row;
import org.zkoss.zul.RowRenderer;
import org.zkoss.zul.Rows;
import org.zkoss.zul.SimpleListModel;
import org.zkoss.zul.South;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbar;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import belajarzk.common.Common;
import belajarzk.database.dao.DaoFactory;
import belajarzk.database.dao.TbmuserDao;
import belajarzk.database.hibernate.HibernateUtil;
import belajarzk.database.model.Tbmrole;
import belajarzk.database.model.Tbmuser;

public class TbmuserAction extends GenericAutowireComposer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7070962748923355504L;
	private Window addWindow;
	private Grid grid;

	private Textbox searchnama;
	private Textbox userNama;
	private Textbox userid;
	private Textbox userPassword;
	private Combobox userRole;
	private Combobox searchrole;

	// private boolean edit = false;
	// private boolean delete = false;

	private Tbmuser tbmuser;
	private Tbmuser tbmuser1;
	private Toolbarbutton add;

	@Override
	public void doAfterCompose(Component comp) throws Exception {
		// TODO Auto-generated method stub
		super.doAfterCompose(comp);

		if (session.getAttribute("usersTemp") == null) {
			execution.sendRedirect("../login.zul");
			return;
		}

		Common.insertCombo(userRole, "roleName", Tbmrole.class);
		Common
				.insertCombo(userRole = new Combobox(), "roleName",
						Tbmrole.class);
		Common.insertCombo(searchrole, "roleName", Tbmrole.class);

		add.setTooltiptext("Tambah");

		onSearchDefault(null);
	}

	class UserRenderer implements RowRenderer {

		@Override
		public void render(final Row arg0, Object arg1) throws Exception {
			// TODO Auto-generated method stub
			final Tbmuser tbmuser = (Tbmuser) arg1;

			new Label(tbmuser.getUserNama()).setParent(arg0);
			new Label(tbmuser.getUserRole().getRoleName()).setParent(arg0);

			Hbox toolbar = new Hbox();
			toolbar.setHeight("40px");
			Toolbarbutton button = new Toolbarbutton("", "/img/edit.gif");
			button.setTooltiptext("Rubah Data");
			// button.setVisible(edit);
			button.addEventListener("onClick", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					init(tbmuser);
					addWindow.setVisible(true);
					addWindow.onModal();
				}

			});
			button.setParent(toolbar);

			button = new Toolbarbutton("", "/img/delete.gif");
			button.setTooltiptext("Hapus Data");
			// button.setVisible(delete);
			button.addEventListener("onClick", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					Messagebox.show("Apakah yakin ingin menghapus data ini ?",
							"Question", Messagebox.OK | Messagebox.CANCEL,
							Messagebox.QUESTION, new EventListener() {

								@Override
								public void onEvent(Event event)
										throws Exception {
									int i = new Integer(event.getData()
											.toString());
									if (i == Messagebox.OK) {
										try {
											TbmuserDao tbmuserDao = DaoFactory
													.getInstance()
													.getTbmuserDao();
											// agamaDao.beginTransaction();
											tbmuserDao.delete(tbmuserDao
													.merge(tbmuser));
											// agamaDao.commitTransaction();
											arg0.detach();
										} catch (Exception e) {
											e.printStackTrace();
											Messagebox
													.show("Data ini tidak dapat dihapus ..");
										}

									}

								}
							});

				}
			});
			button.setParent(toolbar);
			toolbar.setParent(arg0);
		}

	}

	public void onAdd(Event event) throws Exception {
		init(new Tbmuser());
		addWindow.setVisible(true);
		addWindow.onModal();
	}

	private void init(Tbmuser tbmuser) {
		this.tbmuser = tbmuser;
		addWindow.setTitle("Pendataan User");
		Common.clear(addWindow);
		Borderlayout borderlayout = new Borderlayout();
		Center center = new Center();
		center.setParent(borderlayout);
		center.setFlex(true);
		Grid grid = new Grid();
		grid.setParent(center);
		grid.setWidth("100%");
		grid.setHeight("100%");
		grid.setOddRowSclass("non-odd");

		Rows rows = new Rows();
		rows.setParent(grid);

		Row row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("User id"));
		row.appendChild(userid = new Textbox(tbmuser.getUserId() == null ? ""
				: tbmuser.getUserId()));
		userid.setCols(40);

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Nama"));
		row.appendChild(userNama = new Textbox(
				tbmuser.getUserNama() == null ? "" : tbmuser.getUserNama()));
		userNama.setCols(40);

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Password"));
		row.appendChild(userPassword = new Textbox(
				tbmuser.getUserPassword() == null ? "" : tbmuser
						.getUserPassword()));
		userPassword.setType("password");
		userPassword.setCols(40);

		row = new Row();
		row.setStyle("border:0px;background: transparent;");
		row.setParent(rows);
		row.appendChild(new Label("Role"));
		Common.selectComboItem(userRole, tbmuser.getUserRole() == null ? null
				: tbmuser.getUserRole());
		row.appendChild(userRole);
		userRole.setCols(40);

		// row = new Row();
		// row.setStyle("border:0px;background: transparent;");
		// row.setParent(rows);
		// row.appendChild(new Label("Show"));
		// row.appendChild(userShow = new Checkbox());
		// userShow.setChecked(tbmuser.getUserShow() == null ? false : tbmuser
		// .getUserShow().equals(1));
		// userShow.addEventListener("onCheck", new EventListener() {
		// @Override
		// public void onEvent(Event arg0) throws Exception {
		// if (userShow.isChecked()) {
		// userShow.setAttribute("myValue", 1);
		// } else {
		// userShow.setAttribute("myValue", 0);
		// }
		// }
		// });

		// row = new Row();
		// row.setStyle("border:0px;background: transparent;");
		// row.setParent(rows);
		// row.appendChild(new Label("Dosen"));
		// row.appendChild(dosen = new AmbilDataDosenBanbox());
		// dosen.setValue(tbmuser.getDosen() == null ? "" : tbmuser.getDosen()
		// .getNama());
		// dosen.setAttribute("myValue", tbmuser.getDosen());
		// dosen.setCols(40);
		//
		// row = new Row();
		// row.setStyle("border:0px;background: transparent;");
		// row.setParent(rows);
		// row.appendChild(new Label("Fakultas"));
		// Common.selectComboItem(fakultas, tbmuser.getFakultas() == null ?
		// tbmuser1.getFakultas()
		// : tbmuser.getFakultas());
		// row.appendChild(fakultas);
		// fakultas.setCols(40);

		// row = new Row();
		// row.setStyle("border:0px;background: transparent;");
		// row.setParent(rows);
		// row.appendChild(new Label("Program Studi"));
		// Common.selectComboItem(jurusan, tbmuser.getJurusan() == null ?
		// tbmuser1.getJurusan()
		// : tbmuser.getJurusan());
		// row.appendChild(jurusan);
		// jurusan.setCols(40);

		South south = new South();
		south.setFlex(true);
		south.setParent(borderlayout);

		Toolbar toolbar = new Toolbar();
		toolbar.setParent(south);
		Toolbarbutton cancel = new Toolbarbutton("", "/img/left-sign.gif");
		cancel.setTooltiptext("Tutup");
		cancel.addEventListener("onClick", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				addWindow.setVisible(false);
			}
		});
		cancel.setParent(toolbar);
		Toolbarbutton save = new Toolbarbutton("", "/img/save.gif");
		save.setTooltiptext("Simpan");
		save.addEventListener("onClick", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				if (onSave(event)) {
					onSearchDefault(null);
					addWindow.setVisible(false);
				}
			}
		});
		save.setParent(toolbar);
		borderlayout.setParent(addWindow);
		Caption caption = new Caption();
		Toolbarbutton button = new Toolbarbutton(" X ");
		button.addEventListener("onClick", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				addWindow.setVisible(false);
			}

		});
		button.setParent(caption);
		// caption.setParent(addWindow);
	}

	public boolean onSave(Event event) throws Exception {
		if (userNama.getValue().trim().equals("")) {
			Messagebox.show("Username harus diisi", "Peringatan", 1,
					Messagebox.INFORMATION);
			return false;
		}
		if (userPassword.getValue().trim().equals("")) {
			Messagebox.show("Password harus diisi", "Peringatan", 1,
					Messagebox.INFORMATION);
			return false;
		}
		if (userRole.getSelectedItem() == null) {
			Messagebox.show("Role harus dipilih", "Peringatan", 1,
					Messagebox.INFORMATION);
			return false;
		}

		boolean i = checkUser();
		if (i) {
			Messagebox
					.show(
							"Username sudah terpakai,silahkan pilih username yang lain",
							"Peringatan", 1, Messagebox.INFORMATION);
			return false;
		}

		TbmuserDao tbmuserDao = DaoFactory.getInstance().getTbmuserDao();
		if (tbmuser.getUserId() != null) {
			tbmuser = tbmuserDao.load(tbmuser.getUserId());

		}

		tbmuser.setUserId(userid.getValue());
		tbmuser.setUserNama(userNama.getValue());
		tbmuser.setUserPassword(userPassword.getValue());
		tbmuser.setUserRole((Tbmrole) userRole.getSelectedItem().getValue());
		// tbmuser.setUserShow(userShow.isChecked() ? 1 : 0);
		// tbmuser
		// .setDosen((Dosen) (dosen.getSelectedItem() == null ? null
		// : dosen.getSelectedItem().getValue()));
		// tbmuser.setDosen((Dosen) dosen.getAttribute("myValue"));
		// tbmuser.setJurusan((Jurusan) (jurusan.getSelectedItem() == null ?
		// null
		// : jurusan.getSelectedItem().getValue()));
		// tbmuser
		// .setFakultas((Fakultas) (fakultas.getSelectedItem() == null ? null
		// : fakultas.getSelectedItem().getValue()));

		// agamaDao.beginTransaction();
		if (tbmuser.getUserId() != null) {
			tbmuserDao.update(tbmuser);
		} else {
			tbmuserDao.save(tbmuser);
		}
		// agamaDao.commitTransaction();
		return true;
	}

	@SuppressWarnings("unchecked")
	public void onSearchDefault(Event event) {
		Session session = HibernateUtil.currentSession();
		List<Tbmuser> tbmuser = session.createCriteria(Tbmuser.class).addOrder(
				Order.asc("userNama")).add(
				Restrictions.ilike("userNama", searchnama.getValue().trim(),
						MatchMode.ANYWHERE))
		// .add(
				// searchrole.getSelectedItem() == null ? Restrictions
				// .sqlRestriction("1=1") : Restrictions.eq("userRole",
				// searchrole.getSelectedItem().getValue()))
				// .add(Restrictions.eq("userShow", 1))

				.setMaxResults(Common.MAX_RESULT).list();
		ListModel strset = new SimpleListModel(tbmuser);
		grid.setRowRenderer(new UserRenderer());
		grid.setModel(strset);

		grid.renderAll();
		grid.setOddRowSclass("non-odd");

	}

	public Boolean checkUser() {

		Integer userCount = null;
		Session session = HibernateUtil.currentSession();
		userCount = ((Number) session.createCriteria(Tbmuser.class)
				.setProjection(Projections.count("id")).add(
						Restrictions.eq("userId", userid.getValue().trim()))
				.add(
						this.tbmuser.getUserId() == null ? Restrictions
								.sqlRestriction("1=1") : Restrictions.ne("id",
								this.tbmuser.getUserId())).uniqueResult())
				.intValue();

		return !userCount.equals(0);
	}
}
